import urllib
import urllib.request
import json
import fileUtil
import logUtil

def getDataByType(queryType, region, page_num, ak):
    queryType = urllib.parse.quote(queryType)
    region = urllib.parse.quote(region)
    url = 'http://api.map.baidu.com/place/v2/search?ak='+ak+'&output=json&query=' + \
        queryType+'&scope=2&region='+region + \
        '&page_size=20&page_num='+str(page_num)
    response = urllib.request.urlopen(url)
    result = json.loads(response.read().decode())
    return result


def getDataByExtent(queryType, page_num, ak, extent, flag = True):
    jsonStr = None
    try:
        baseQueryType = urllib.parse.quote(queryType)
        url = 'http://api.map.baidu.com/place/v2/search?ak='+ak+'&output=json&tag='+baseQueryType+'&query='+baseQueryType+'&scope=2&page_size=20&page_num=' + \
            str(page_num)+"&bounds="+(",".join(str(i) for i in extent))
        #     str(page_num)+"&bounds="+str(extent)
        response = urllib.request.urlopen(url, timeout=10)
        jsonStr = response.read().decode()
       # result = json.loads(jsonStr)
        result = eval(jsonStr)
        return result
    except TimeoutError:
        if flag:
            fileUtil.timeoutRequest(queryType,page_num,ak,extent).save()
    except BaseException:
        logUtil.logger.warning('响应值json:%s', jsonStr)
        if flag:
            fileUtil.timeoutRequest(queryType,page_num,ak,extent).save()
       # raise e

def fetchDataIsLoss(reponseData):
    total = reponseData['total']
    return total >= 400

def getSplitExtent(extent, splitCount, idx):
    x_ratio = (extent[3] - extent[1]) / splitCount
    return [extent[0], extent[1] + idx * x_ratio, extent[2],  extent[1] + (idx + 1) * x_ratio]

def isValidRequest(reponseData):
    status = reponseData['status']
    return status == 0